package com.bd.scm.module.department.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bd.scm.domain.dto.department.DeptAgGridTree;
import com.bd.scm.domain.dto.tree.ZTree;
import com.bd.scm.domain.models.department.DtDep;
import com.bd.scm.module.common.BaseController;
import com.bd.scm.module.department.service.IDtDepService;
import com.bd.scm.module.enums.ExceptionEmun;
import com.bd.scm.module.utils.EhcacheUtil;
import com.bd.scm.module.utils.ResultUtil;
import com.bd.utils.exception.BdException;
import com.bd.utils.vo.Result;
import io.swagger.annotations.Api;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiSort;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 部门前端控制器
 *
 * @author yufc
 * @since 2019-08-27
 */
@RestController
@RequestMapping("/api/dept")
@Api(tags = "部门接口")
@ApiSort(value = 2)
public class DtDepController extends BaseController {

    private Logger log = LoggerFactory.getLogger("dataLogger");

    @Autowired
    private IDtDepService iDtDepService;


    @GetMapping("tree")
    @ApiOperation(value = "获取部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取部门树结构数据（只有key、title、children）", produces = "application/json")
    public Result getDeptTree(
            @ApiParam(name = "pid", value = "上级部门ID", required = false, defaultValue = "0")
            @RequestParam(name = "pid", defaultValue = "0") Long parentId) {
        return ResultUtil.ok(iDtDepService.getDeptTreeList(parentId));
    }


    @GetMapping("treedata")
    public Result getDeptTreeWithData(@RequestParam(name = "pid", defaultValue = "0") Long parentId) {
        return ResultUtil.ok(iDtDepService.getDeptTreeListWithData(parentId));
    }

    @GetMapping("tree/jobZTree")
    @ApiOperation(value = "获取岗位树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取岗位树结构数据", produces = "application/json")
    public Result getJobZTree(
            @ApiParam(name = "pid", value = "上级岗位ID", required = false, defaultValue = "0")
            @RequestParam(name = "pid", defaultValue = "NULL") String parentId,HttpServletRequest request)  {
        //获取登录对象
        JSONObject userInfo = (JSONObject) request.getSession().getAttribute("user");

        if (userInfo == null) {
            log.error("============== 获取岗位树数据： 登录超时 ==============");
            return ResultUtil.errorLogin();
        }

        List<ZTree> treeList;

        //根据登录人的ID 去缓存中是否能找到相关信息
        String userDept = EhcacheUtil.get(userInfo.getString("userSerial")+"_Job");

        if (StringUtils.isEmpty(userDept)){

            treeList = iDtDepService.getJobList(parentId);

            // 设置缓存
            EhcacheUtil.put(userInfo.getString("userSerial")+"_Job", JSONObject.toJSONString(treeList));
        } else {
            // 从缓存取数据
            treeList = JSONArray.parseArray(userDept, ZTree.class);
        }
        return ResultUtil.ok(treeList);
    }

    @GetMapping("tree/zTree")
    @ApiOperation(value = "获取部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取部门树结构数据", produces = "application/json")
    public Result getZTree(
            @ApiParam(name = "pid", value = "上级部门ID", required = false, defaultValue = "0")
            @RequestParam(name = "pid", defaultValue = "0") Long parentId,HttpServletRequest request)  {
        //获取登录对象
        JSONObject userInfo = (JSONObject) request.getSession().getAttribute("user");

        if (userInfo == null) {
            log.error("============== 获取部门树数据： 登录超时 ==============");
            return ResultUtil.errorLogin();
        }

        List<String> deptIdList;
        List<ZTree> treeList;

        //根据登录人的ID 去缓存中是否能找到相关信息
        String userDept = EhcacheUtil.get(userInfo.getString("userSerial"));

        if (StringUtils.isEmpty(userDept)){

            // 没有缓存重新从数据库中获取数据
            deptIdList = JSONArray.parseArray(String.valueOf(request.getSession().getAttribute("findDeptid")), String.class);

            treeList = iDtDepService.getZTreeList(parentId, deptIdList);

            // 设置缓存
            if(null!=treeList){
                EhcacheUtil.put(userInfo.getString("userSerial"), JSONObject.toJSONString(treeList));
            }
        } else {
            // 从缓存取数据
            treeList = JSONArray.parseArray(userDept, ZTree.class);
        }

        return ResultUtil.ok(treeList);

    }

    @GetMapping("tree/findDepList")
    @ApiOperation(value = "获取2级部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取部门树结构数据", produces = "application/json")
    public Result findDepList(
        @ApiParam(name = "pid", value = "上级部门ID", required = false, defaultValue = "0")
        @RequestParam(name = "pid", defaultValue = "0") Long parentId,HttpServletRequest request) {
        List<String> deptIdList = JSONArray.parseArray(String.valueOf(request.getSession().getAttribute("findDeptid")), String.class);
        return ResultUtil.ok(iDtDepService.findDepList(parentId,deptIdList));
    }

    @GetMapping("tree/findGlDepList")
    @ApiOperation(value = "获取2级规律班次部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取2级规律班次部门树结构数据", produces = "application/json")
    public Result findGlDepList(
            @ApiParam(name = "pid", value = "上级部门ID", required = false, defaultValue = "0")
            @RequestParam(name = "pid", defaultValue = "0") Long parentId,HttpServletRequest request) {
        List<String> deptIdList = JSONArray.parseArray(String.valueOf(request.getSession().getAttribute("findDeptid")), String.class);
        return ResultUtil.ok(iDtDepService.findGlDepList(parentId,deptIdList));
    }

    @PutMapping
    public Result edit(@RequestBody DtDep dept, HttpServletRequest request) {
        log.info("部门修改,接收数据---{}", JSON.toJSON(dept));

        int iResult = iDtDepService.edit(dept);

        log.info("部门修改结果---{}", iResult > 0 ? "成功" : "失败");

        return iResult > 0 ? ResultUtil.ok() : ResultUtil.error("更新部门失败");
    }

    @PostMapping("addDtDep")
    public Result add(@RequestBody DtDep dept, HttpServletRequest request) {
        log.info("部门新增,接收数据---{}", JSON.toJSON(dept));

        int iResult = iDtDepService.add(dept);

        log.info("部门新增结果---{}", iResult > 0 ? "成功" : "失败");

        return iResult > 0 ? ResultUtil.ok() : ResultUtil.error("新增部门失败");
    }

    @DeleteMapping
    @RequestMapping("delete")
    public Result delete(@RequestBody DtDep dept, HttpServletRequest request){
        log.info("部门删除,接收数据---{}", JSON.toJSON(dept));
        String flag = iDtDepService.delete(dept);
        if(null != flag){
            return ResultUtil.error(flag);
        }else{
            return ResultUtil.ok();
        }
//        int iResult = iDtDepService.delete(dept);
//
//        log.info("部门删除结果---{}", iResult > 0 ? "成功" : "失败");
//
//        return iResult > 0 ? ResultUtil.ok() : ResultUtil.error("删除部门失败");
    }

    @GetMapping("treekey")
    public Result getParent(String key) {
        log.info("部门搜索,接收关键字---{}", key);

        List<String> keyList = iDtDepService.searchTreeKeyList(key);

        log.info("部门搜索结果---{}", JSON.toJSON(keyList));

        return ResultUtil.ok(keyList);
    }

    @GetMapping("agTree")
    public Result getAgGridTreeData(@RequestParam(name = "depName", defaultValue = "") String depName) {
        List<DeptAgGridTree> agTreeGridList = iDtDepService.getAgTreeGridList(depName);

        return ResultUtil.ok(agTreeGridList);
    }

    @PostMapping("deleteDtDep")
    public Result deleteDtDep(@RequestBody DtDep dept, HttpServletRequest request){
        log.info("部门删除,接收数据---{}", JSON.toJSON(dept));
        String flag = iDtDepService.deleteDtDep(dept);
        if(null != flag){
            return ResultUtil.error(flag);
        }else{
            return ResultUtil.ok();
        }
    }

    @PostMapping("updateDtDep")
    public Result updateDtDep(@RequestBody DtDep dept, HttpServletRequest request){
        log.info("部门修改,接收数据---{}", JSON.toJSON(dept));
        String flag = iDtDepService.updateDtDep(dept);
        if(null != flag){
            return ResultUtil.error(flag);
        }else{
            return ResultUtil.ok();
        }
    }

    @GetMapping("tree/zTreeAll")
    @ApiOperation(value = "获取全部的部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取全部的部门树结构数据", produces =
            "application/json")
    public Result getZTreeAll(
            @ApiParam(name = "pid", value = "上级部门ID", required = false, defaultValue = "0")
            @RequestParam(name = "pid", defaultValue = "0") Long parentId, HttpServletRequest request) {

        List<String> deptIdList = new ArrayList<>();
        List<ZTree> treeList = iDtDepService.getZTreeList(parentId, deptIdList);

        return ResultUtil.ok(treeList);
    }

    /**
     * 移动端调用
     * @param serchValue
     * @return
     */
    @GetMapping("findDtDepList")
    @ApiOperation(value = "移动端获取部门树结构数据", httpMethod = "GET", protocols = "HTTP", notes = "获取部门树结构数据（只有depSerial,depName,depNo）", produces = "application/json")
    public Result findDtDepList(
            @ApiParam(name = "serchValue", value = "(部门名称或者编号)", required = false, defaultValue = "")
            @RequestParam(name = "serchValue", defaultValue = "") String serchValue) {
        return ResultUtil.ok(iDtDepService.findDtDepList(serchValue));
    }
}
